<template>
    <div class="fridge-page">
        <!-- 操作按钮区 -->
        <div class="btn-group">
            <el-button :icon="Back" @click="handleBack">返回</el-button>
            <el-button type="success" :icon="ScaleToOriginal" @click="openShelfDialog">生成分区(存冻架)</el-button>
            <el-button type="success" :icon="ScaleToOriginal" @click="openBoxDialog" v-if="hasGeneratedShelf">
                批量生成冻存盒
            </el-button>
        </div>

        <!-- 表格水平排列容器 -->
        <div class="table-container">
            <!-- 1. 冰箱分区（冻存架） -->
            <div class="table-section">
                <h3>1. 冰箱分区(冻存架)
                    <el-button type="primary" size="mini" :icon="Edit">编辑</el-button>
                </h3>
                <el-skeleton v-if="loadingShelf" :rows="rowNums" style="width: 100%;" />
                <el-table v-else :data="freezerRackData" border style="width: 100%; margin-bottom: 20px;"
                    @cell-click="handleRackCellClick">
                    <el-table-column prop="rowLabel" label="X" width="60" />
                    <el-table-column v-for="col in columnNums" :key="col" :prop="'col' + col" :label="col" width="80"
                        :cell-class-name="(params) => getRackCellClass(params, col)" />
                </el-table>
                <div class="selected-tip">选中：{{ selectedRackInfo || '未选中' }}</div>
            </div>

            <!-- 2. 冻存盒（仅生成冻存架后显示） -->
            <div class="table-section" v-if="hasGeneratedShelf">
                <h3>2. 冻存盒
                    <el-button type="primary" size="mini" :icon="Edit">编辑</el-button>
                </h3>
                <el-skeleton v-if="loadingBox" :rows="rowNums" style="width: 100%;" />
                <el-table v-else :data="storageBoxData" border style="width: 100%; margin-bottom: 20px;"
                    @cell-click="handleBoxCellClick">
                    <el-table-column prop="rowLabel" label="X" width="60" />
                    <el-table-column v-for="col in columnNums" :key="col" :prop="'col' + col" :label="col" width="80"
                        :cell-class-name="(params) => getBoxCellClass(params, col)" />
                </el-table>
                <div class="selected-tip">选中：{{ selectedBoxInfo || '未选中' }}</div>
            </div>

            <!-- 3. 样本（仅生成冻存盒后显示） -->
            <div class="table-section" v-if="hasGeneratedBox">
                <h3>3. 样本
                    <el-button type="primary" size="mini" :icon="Edit" @click="openBoxSamples">打开冻存盒</el-button>
                    <el-button type="primary" size="mini" :icon="Edit">编辑样本</el-button>
                </h3>
                <el-skeleton v-if="loadingSample" :rows="11" style="width: 100%;" />
                <table class="el-table el-table--border" style="width: 100%;">
                    <tr v-for="(row, rowIndex) in sampleData" :key="rowIndex">
                        <td v-for="(cell, colIndex) in row" :key="colIndex"
                            @click="handleSampleCellClick({ $index: rowIndex }, { index: colIndex + 1 })"
                            :class="getSampleCellClass({ $index: rowIndex }, colIndex + 1)"
                            style="width: 60px; text-align: center;">
                            {{ cell }}
                        </td>
                    </tr>
                </table>
            </div>
        </div>

        <!-- 生成分区(存冻架)模态框 -->
        <el-dialog v-model="dialogVisible" :title="title" width="55%">
            <div style="display: flex; justify-content: center;">
                <el-form ref="ruleFormRef" style="width: 100%; max-width: 900px;" :model="ruleForm" :rules="rules"
                    label-width="100px">
                    <div
                        style="display: flex; justify-content: space-between; padding: 12px 0; border-bottom: 1px solid #f0f0f0;">
                        <el-form-item label="规格型号" style="width: 48%;" prop="shelfTypeName">
                            <el-input v-model="ruleForm.shelfTypeName" placeholder="规格型号" readonly>
                                <template #append>
                                    <el-button :icon="Search" @click="openShelfTypeDialog" />
                                </template>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="类型" style="width: 48%;">
                            <span>按冰箱生成({{ freezerRackData.length }}个)</span>
                        </el-form-item>
                    </div>
                    <div
                        style="display: flex; justify-content: space-between; padding: 12px 0; border-bottom: 1px solid #f0f0f0;">
                        <el-form-item label="行数" style="width: 48%;" prop="rowNums">
                            <el-input v-model.number="ruleForm.rowNums" placeholder="行数" />
                        </el-form-item>
                        <el-form-item label="列数" style="width: 48%;" prop="columnNums">
                            <el-input v-model.number="ruleForm.columnNums" placeholder="列数" />
                        </el-form-item>
                    </div>
                    <div style="padding: 12px 0;">
                        <el-form-item label="备注" prop="remark">
                            <el-input v-model="ruleForm.remark" type="textarea" rows="3" />
                        </el-form-item>
                    </div>
                    <el-form-item style="text-align: right; margin-top: 20px;">
                        <el-button @click="resetShelfForm">取消</el-button>
                        <el-button type="primary" @click="submitShelfForm">确定</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </el-dialog>

        <!-- 规格型号模态框 -->
        <el-dialog v-model="dialogVisibleShelfType" :title="titleShelfType" width="55%">
            <el-row :gutter="10">
                <el-col :span="10">
                    <div style="display: flex; gap: 10px">
                        <el-input placeholder="参数名" clearable v-model="shelfTypeSearch.key" />
                        <el-button @click="searchShelfType">查询</el-button>
                    </div>
                </el-col>
            </el-row>

            <el-table :data="shelfTypes" row-key="id" style="width: 100%;" border>
                <el-table-column property="name" label="名称" />
                <el-table-column property="rowNums" label="行数" />
                <el-table-column property="columnNums" label="列数" />
                <el-table-column property="encodingType" label="位置编码类型" />
                <el-table-column property="width" label="宽度" />
                <el-table-column property="height" label="高度" />
                <el-table-column property="remark" label="备注" />
                <el-table-column label="操作" fixed="right" width="180">
                    <template #default="scope">
                        <el-button @click="selectShelfType(scope.row)">选择</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination v-model:current-page="shelfTypePage.page" v-model:page-size="shelfTypePage.limit"
                :page-sizes="[10, 20, 50, 100]" :background="true" layout="total, sizes, prev, pager, next, jumper"
                :total="shelfTypeTotal" @size-change="handleShelfTypeSizeChange"
                @current-change="handleShelfTypePageChange" style="margin-top: 20px;" />
        </el-dialog>

        <!-- 生成存冻盒模态框 -->
        <el-dialog v-model="dialogVisibleBox" :title="titleBox" width="55%">
            <el-form ref="boxFormRef" :model="boxForm" :rules="boxRules" label-width="100px">
                <div
                    style="display: flex; justify-content: space-between; padding: 12px 0; border-bottom: 1px solid #f0f0f0;">
                    <el-form-item label="冻存盒规格" style="width: 48%;" prop="boxTypeName">
                        <el-input v-model="boxForm.boxTypeName" placeholder="冻存盒类型" readonly>
                            <template #append>
                                <el-button :icon="Search" @click="openBoxTypeDialog" />
                            </template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="选中冻存架" style="width: 48%;">
                        <span>{{ selectedRackInfo || '请先选择冻存架' }}</span>
                    </el-form-item>
                </div>
                <div
                    style="display: flex; justify-content: space-between; padding: 12px 0; border-bottom: 1px solid #f0f0f0;">
                    <el-form-item label="行数" style="width: 48%;" prop="rowNums">
                        <el-input v-model.number="boxForm.rowNums" placeholder="行数" />
                    </el-form-item>
                    <el-form-item label="列数" style="width: 48%;" prop="columnNums">
                        <el-input v-model.number="boxForm.columnNums" placeholder="列数" />
                    </el-form-item>
                </div>
                <div style="padding: 12px 0;">
                    <el-form-item label="备注" prop="remark">
                        <el-input v-model="boxForm.remark" type="textarea" rows="3" />
                    </el-form-item>
                </div>
                <el-form-item style="text-align: right; margin-top: 20px;">
                    <el-button @click="resetBoxForm">取消</el-button>
                    <el-button type="primary" @click="submitBoxForm" :loading="loadingBoxSubmit">确定</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>

        <!-- 冻存盒规格模态框 -->
        <el-dialog v-model="dialogVisibleBoxType" :title="titleBoxType" width="55%">
            <el-row :gutter="10">
                <el-col :span="10">
                    <div style="display: flex; gap: 10px">
                        <el-input placeholder="搜索规格名称" clearable v-model="boxTypeSearch.key" />
                        <el-button @click="searchBoxType">查询</el-button>
                    </div>
                </el-col>
            </el-row>
            <el-table :data="boxTypes" row-key="id" style="width: 100%;" border @row-click="handleBoxTypeRowClick">
                <el-table-column property="name" label="名称" />
                <el-table-column property="encodingType" label="位置编码">
                    <template #default="scope">
                        <span v-if="scope.row.encodingType === 1">纯数字</span>
                        <span v-else-if="scope.row.encodingType === 2">混合</span>
                    </template>
                </el-table-column>
                <el-table-column property="rowNums" label="行数" />
                <el-table-column property="columnNums" label="列数" />
                <el-table-column property="width" label="宽度" />
                <el-table-column property="height" label="高度" />
                <el-table-column property="remark" label="备注" />
                <el-table-column label="操作" fixed="right" width="100">
                    <template #default="scope">
                        <el-button size="small" @click="selectBoxType(scope.row)">选择</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination v-model:current-page="boxTypePage.page" v-model:page-size="boxTypePage.limit"
                :page-sizes="[10, 20, 50, 100]" :background="true" layout="total, sizes, prev, pager, next, jumper"
                :total="boxTypeTotal" @size-change="handleBoxTypeSizeChange" @current-change="handleBoxTypePageChange"
                style="margin-top: 20px;" />
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, reactive } from 'vue';
import { ElMessage, FormInstance, FormRules } from 'element-plus';
import { Back, ScaleToOriginal, Edit, Search } from '@element-plus/icons-vue';
import { useRouter, useRoute } from 'vue-router';
import {
    detail,
    shelfTypeList,
    batchAddForzenShelf,
    getShelfByEquipmentId,
    batchAddForzenBox,
    getBoxByShelfId,
    getSamplesByBoxId,
    forzenboxtype
} from '@/api/equipment-edit';

// 路由和基础参数
const router = useRouter();
const route = useRoute();
const equipmentId = route.query.id as string; // 冰箱ID
const rowNums = ref(0); // 动态从接口获取
const columnNums = ref(0); // 动态从接口获取
const loadingShelf = ref(true);
const loadingBox = ref(false);
const loadingSample = ref(false);
const loadingBoxSubmit = ref(false);

// 控制表格显示的状态
const hasGeneratedShelf = ref(false);
const hasGeneratedBox = ref(false);

// 选中信息与高亮状态记录
const selectedRackInfo = ref('');
const selectedRack = ref<any>(null);
const selectedRackCell = ref<{ rowIndex: number, columnIndex: number } | null>(null); // 冻存架选中单元格位置

const selectedBoxInfo = ref('');
const selectedBoxId = ref('');
const selectedBoxCell = ref<{ rowIndex: number, columnIndex: number } | null>(null); // 冻存盒选中单元格位置

const selectedSampleCell = ref<{ rowIndex: number, columnIndex: number } | null>(null); // 样本选中单元格位置

// 数据列表
const freezerRackData = ref<any[]>([]);
const storageBoxData = ref<any[]>([]);
const sampleData = ref<any[]>([]);

// 冻存架相关表单
const dialogVisible = ref(false);
const title = ref('生成分区(存冻架)');
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive({
    genType: 1,
    equipmentId: '',
    selectRow: 1,
    selectColumn: 1,
    rowNums: 0, // 动态赋值
    columnNums: 0, // 动态赋值
    shelfTypeId: '',
    shelfTypeName: '',
    remark: ''
});

// 冻存架规格选择
const dialogVisibleShelfType = ref(false);
const titleShelfType = ref('选择冻存架类型');
const shelfTypes = ref<any[]>([]);
const shelfTypeTotal = ref(0);
const shelfTypePage = reactive({
    page: 1,
    limit: 10
});
const shelfTypeSearch = reactive({ key: '' });

// 冻存盒相关表单
const dialogVisibleBox = ref(false);
const titleBox = ref('批量生成冻存盒');
const boxFormRef = ref<FormInstance>();
const boxForm = reactive({
    equipmentId: '',
    shelfId: '',
    boxTypeId: '',
    boxTypeName: '',
    rowNums: 12,
    columnNums: 10,
    remark: '',
});

// 冻存盒规格选择
const dialogVisibleBoxType = ref(false);
const titleBoxType = ref('选择冻存盒规格');
const boxTypes = ref<any[]>([]);
const boxTypeTotal = ref(0);
const boxTypePage = reactive({
    page: 1,
    limit: 10
});
const boxTypeSearch = reactive({ key: '' });

// 页面初始化
onMounted(async () => {
    if (!equipmentId) {
        ElMessage.error('缺少设备ID');
        return;
    }
    try {
        // 调用冰箱详情接口
        const equipRes = await detail(equipmentId);
        if (equipRes.code === 0) {
            const equipment = equipRes.equipment;
            console.log('接口返回的设备信息:', equipment); // 调试日志

            // 从接口数据中读取行列数
            rowNums.value = equipment.rowNums || 6; // 默认6行
            columnNums.value = equipment.columnNums || 4; // 默认4列

            // 初始化表单数据
            ruleForm.equipmentId = equipmentId;
            ruleForm.rowNums = rowNums.value;
            ruleForm.columnNums = columnNums.value;

            boxForm.equipmentId = equipmentId;
        } else {
            console.error('获取设备详情失败:', equipRes.msg);
            ElMessage.error('获取设备信息失败');
            // 设置默认行列数
            rowNums.value = 6;
            columnNums.value = 4;
        }

        // 获取已有冻存架
        await getFreezerRackList();
        if (freezerRackData.value.length > 0) {
            hasGeneratedShelf.value = true;
            // 默认选中第一个冻存架
            const firstRack = freezerRackData.value[0];
            if (firstRack) {
                handleRackCellClick(firstRack, { index: 1 }, null, new Event('click'));
            }
        }

        generateSampleData();
    } catch (error) {
        console.error('页面初始化失败', error);
        ElMessage.error('加载失败，请重试');

        // 设置默认行列数
        rowNums.value = 6;
        columnNums.value = 4;
    }
});

// 冻存架表格：单元格点击事件（高亮+调用接口）
const handleRackCellClick = (row: any, column: any, cell: any, event: Event) => {
    // 记录选中位置（用于高亮）
    selectedRackCell.value = {
        rowIndex: row.$index,
        columnIndex: column.index
    };
    // 更新选中信息
    selectedRackInfo.value = `${row.rowLabel}区 (${row.code})`;
    selectedRack.value = row;
    // 选中后调用冻存盒接口
    getStorageBoxList(row.id);
};

// 冻存架单元格高亮类
const getRackCellClass = (params: any, col: number) => {
    if (selectedRackCell.value &&
        params.row.$index === selectedRackCell.value.rowIndex &&
        col === selectedRackCell.value.columnIndex) {
        return 'cell-highlight';
    }
    return '';
};

// 冻存盒表格：单元格点击事件（高亮+调用接口）
const handleBoxCellClick = (row: any, column: any) => {
    const colIndex = parseInt(column.label);
    const boxCode = row[`col${colIndex}`];

    if (!boxCode) return;

    // 记录选中位置
    selectedBoxCell.value = {
        rowIndex: row.$index,
        columnIndex: colIndex
    };

    selectedBoxInfo.value = `冻存盒(${boxCode})`;
    selectedBoxId.value = boxCode;
    openBoxSamples();
};

// 冻存盒单元格高亮类
const getBoxCellClass = (params: any, col: number) => {
    if (selectedBoxCell.value &&
        params.row.$index === selectedBoxCell.value.rowIndex &&
        col === selectedBoxCell.value.columnIndex) {
        return 'cell-highlight';
    }
    return '';
};

// 样本表格：单元格点击事件（仅高亮）
const handleSampleCellClick = (row: any, column: any) => {
    // 记录选中位置（用于高亮）
    selectedSampleCell.value = {
        rowIndex: row.$index,
        columnIndex: column.index
    };
};

// 样本单元格高亮类
const getSampleCellClass = (params: any, col: number) => {
    if (selectedSampleCell.value &&
        params.$index === selectedSampleCell.value.rowIndex &&
        col === selectedSampleCell.value.columnIndex) {
        return 'cell-highlight';
    }
    return '';
};

// 打开冻存架规格选择框
const openShelfTypeDialog = () => {
    dialogVisibleShelfType.value = true;
    getShelfTypeList();
};

// 获取冻存架规格列表
const getShelfTypeList = async () => {
    try {
        const res = await shelfTypeList({ ...shelfTypePage, key: shelfTypeSearch.key });
        if (res.code === 0) {
            shelfTypes.value = res.page.list || [];
            shelfTypeTotal.value = res.page.totalCount || 0;
        } else {
            ElMessage.error(res.msg || '获取类型列表失败');
        }
    } catch (error) {
        console.error('获取类型列表失败', error);
    }
};

// 搜索冻存架规格
const searchShelfType = () => {
    shelfTypePage.page = 1;
    getShelfTypeList();
};

// 分页变更
const handleShelfTypeSizeChange = (val: number) => {
    shelfTypePage.limit = val;
    shelfTypePage.page = 1;
    getShelfTypeList();
};
const handleShelfTypePageChange = (val: number) => {
    shelfTypePage.page = val;
    getShelfTypeList();
};

// 选择冻存架规格
const selectShelfType = (row: any) => {
    ruleForm.shelfTypeId = row.id;
    ruleForm.shelfTypeName = row.name;
    ruleForm.rowNums = row.rowNums;
    ruleForm.columnNums = row.columnNums;
    dialogVisibleShelfType.value = false;
};

// 获取冻存架列表
const getFreezerRackList = async () => {
    try {
        loadingShelf.value = true;
        const res = await getShelfByEquipmentId(equipmentId);
        if (res.code === 0) {
            freezerRackData.value = res.forzenShelfs || [];
            freezerRackData.value.forEach((item, index) => {
                item.rowLabel = String.fromCharCode(65 + index);
            });
        } else {
            ElMessage.error(res.msg || '获取冻存架失败');
        }
    } catch (error) {
        console.error('获取冻存架失败', error);
        ElMessage.error('获取冻存架失败');
    } finally {
        loadingShelf.value = false;
    }
};

// 提交冻存架表单
const submitShelfForm = async () => {
    if (!ruleFormRef.value) return;
    await ruleFormRef.value.validate(async (valid) => {
        if (valid) {
            try {
                const res = await batchAddForzenShelf(ruleForm);
                if (res.code === 0) {
                    ElMessage.success('生成分区成功');
                    dialogVisible.value = false;
                    await getFreezerRackList();
                    hasGeneratedShelf.value = true;
                } else {
                    ElMessage.error(res.msg || '生成分区失败');
                }
            } catch (error) {
                console.error('生成分区失败', error);
                ElMessage.error('生成分区失败');
            }
        }
    });
};

// 重置冻存架表单
const resetShelfForm = () => {
    ruleFormRef.value?.resetFields();
    dialogVisible.value = false;
};

// 打开冻存盒生成对话框
const openBoxDialog = () => {
    if (!selectedRack.value) {
        ElMessage.warning('请先选择冻存架');
        return;
    }
    // 重置表单，保留选中的冻存架关联
    boxForm.shelfId = selectedRack.value.id;
    boxForm.boxTypeId = '';
    boxForm.boxTypeName = '';
    boxForm.remark = '';
    dialogVisibleBox.value = true;
    nextTick(() => {
        boxFormRef.value?.resetFields();
    });
};

// 打开冻存盒规格选择框
const openBoxTypeDialog = () => {
    dialogVisibleBoxType.value = true;
    boxTypePage.page = 1;
    searchBoxType();
};

// 查询冻存盒规格
const searchBoxType = async () => {
    try {
        const res = await forzenboxtype({ ...boxTypePage, key: boxTypeSearch.key });
        if (res.code === 0) {
            boxTypes.value = res.page.list || [];
            boxTypeTotal.value = res.page.totalCount || 0;
        } else {
            ElMessage.error(res.msg || '获取冻存盒规格失败');
        }
    } catch (error) {
        console.error('获取冻存盒规格失败', error);
        ElMessage.error('获取冻存盒规格失败');
    }
};

// 行点击选中规格
const handleBoxTypeRowClick = (row: any) => {
    selectBoxType(row);
};

// 选择冻存盒规格
const selectBoxType = (row: any) => {
    boxForm.boxTypeId = row.id;
    boxForm.boxTypeName = row.name;
    boxForm.rowNums = row.rowNums;
    boxForm.columnNums = row.columnNums;
    dialogVisibleBoxType.value = false;
};

// 分页变更
const handleBoxTypeSizeChange = (val: number) => {
    boxTypePage.limit = val;
    boxTypePage.page = 1;
    searchBoxType();
};
const handleBoxTypePageChange = (val: number) => {
    boxTypePage.page = val;
    searchBoxType();
};

// 冻存盒表单验证规则
const boxRules = reactive<FormRules<typeof boxForm>>({
    boxTypeName: [
        { required: true, message: '请选择冻存盒规格', trigger: ['blur', 'change'] }
    ],
    rowNums: [
        { required: true, type: 'number', min: 1, message: '行数必须为正整数', trigger: ['blur', 'change'] }
    ],
    columnNums: [
        { required: true, type: 'number', min: 1, message: '列数必须为正整数', trigger: ['blur', 'change'] }
    ]
});

// 格式化冻存盒数据函数
const formatBoxData = (boxes: any[]) => {
    const formatted: any[] = [];

    // 根据冰箱的行列数初始化空表格
    for (let i = 1; i <= rowNums.value; i++) {
        const rowLabel = String.fromCharCode(64 + i); // A, B, C...
        const rowData: any = { rowLabel };

        for (let j = 1; j <= columnNums.value; j++) {
            // 查找对应位置的冻存盒
            const box = boxes.find(b => {
                const parts = b.code.split('-');
                return parts.length > 1 &&
                    parseInt(parts[1]) === i &&
                    parseInt(parts[2]) === j;
            });

            rowData[`col${j}`] = box ? box.code : '';
        }
        formatted.push(rowData);
    }
    return formatted;
};

// 获取冻存盒列表
const getStorageBoxList = async (shelfId: string) => {
    try {
        loadingBox.value = true;
        const res = await getBoxByShelfId(shelfId);
        if (res.code === 0) {
            const boxes = res.forzenBoxs || [];
            storageBoxData.value = formatBoxData(boxes);
            hasGeneratedBox.value = boxes.length > 0;

            // 默认选中第一个冻存盒
            if (boxes.length > 0 && !selectedBoxId.value) {
                const firstRow = storageBoxData.value[0];
                if (firstRow) {
                    const firstCol = Object.keys(firstRow).find(key => key.startsWith('col'));
                    if (firstCol) {
                        const colIndex = parseInt(firstCol.replace('col', ''));
                        handleBoxCellClick(firstRow, { label: colIndex });
                    }
                }
            }
        } else {
            ElMessage.error(res.msg || '获取冻存盒失败');
        }
    } catch (error) {
        console.error('获取冻存盒失败', error);
        ElMessage.error('获取冻存盒失败');
    } finally {
        loadingBox.value = false;
    }
};

// 提交冻存盒表单
const submitBoxForm = async () => {
    if (!boxFormRef.value) return;

    await boxFormRef.value.validate(async (valid) => {
        if (valid) {
            try {
                loadingBoxSubmit.value = true;
                // 构造接口所需参数
                const submitData = {
                    equipmentId: boxForm.equipmentId,
                    shelfId: boxForm.shelfId,
                    boxTypeId: boxForm.boxTypeId,
                    rowNums: boxForm.rowNums,
                    columnNums: boxForm.columnNums,
                    remark: boxForm.remark
                };
                const res = await batchAddForzenBox(submitData);
                if (res.code === 0) {
                    ElMessage.success('生成冻存盒成功');
                    dialogVisibleBox.value = false;
                    // 重新获取当前冻存架下的冻存盒列表
                    await getStorageBoxList(boxForm.shelfId);
                    hasGeneratedBox.value = true;
                } else {
                    ElMessage.error(res.msg || '生成冻存盒失败');
                }
            } catch (error) {
                console.error('生成冻存盒失败', error);
                ElMessage.error('生成冻存盒失败');
            } finally {
                loadingBoxSubmit.value = false;
            }
        }
    });
};

// 重置冻存盒表单
const resetBoxForm = () => {
    boxFormRef.value?.resetFields();
    dialogVisibleBox.value = false;
};

// 样本数据格式化函数
const formatSampleData = (boxCells: any[]) => {
    sampleData.value = [];
    for (let i = 0; i < 11; i++) {
        const rowLabel = String.fromCharCode(65 + i);
        const sampleRow: any[] = [rowLabel];
        for (let j = 1; j <= 10; j++) {
            const cell = boxCells.find(c => c.row === i + 1 && c.col === j);
            sampleRow.push(cell ? cell.sampleId : '');
        }
        sampleData.value.push(sampleRow);
    }
};

// 生成样本数据（默认空数据）
const generateSampleData = () => {
    sampleData.value = [];
    for (let i = 0; i < 11; i++) {
        const row = [String.fromCharCode(65 + i)];
        for (let j = 1; j <= 10; j++) {
            row.push('');
        }
        sampleData.value.push(row);
    }
};

// 打开冻存盒样本
const openBoxSamples = async () => {
    if (!selectedBoxId.value) {
        ElMessage.warning('请先选择冻存盒');
        return;
    }
    try {
        loadingSample.value = true;
        const res = await getSamplesByBoxId(selectedBoxId.value);
        if (res.code === 0) {
            const boxCells = res.boxCells || [];
            formatSampleData(boxCells);
        } else {
            ElMessage.error(res.msg || '获取样本失败');
        }
    } catch (error) {
        console.error('获取样本失败', error);
        ElMessage.error('获取样本失败');
    } finally {
        loadingSample.value = false;
    }
};

// 返回按钮
const handleBack = () => {
    router.back();
};

// 打开生成分区模态框
const openShelfDialog = () => {
    console.log('尝试打开模态框'); // 调试日志
    dialogVisible.value = true;

    // 重置表单并同步当前行列数
    nextTick(() => {
        ruleFormRef.value?.resetFields();
        ruleForm.rowNums = rowNums.value;
        ruleForm.columnNums = columnNums.value;
        console.log('表单重置后:', ruleForm); // 调试日志
    });
};

// 表单验证规则
const rules = reactive<FormRules<typeof ruleForm>>({
    shelfTypeName: [
        { required: true, message: '请选择规格型号', trigger: ['blur', 'change'] }
    ],
    rowNums: [
        { required: true, type: 'number', min: 1, message: '请输入有效的行数', trigger: ['blur', 'change'] }
    ],
    columnNums: [
        { required: true, type: 'number', min: 1, message: '请输入有效的列数', trigger: ['blur', 'change'] }
    ]
});
</script>

<style scoped>
.fridge-page {
    padding: 20px;
}

/* 按钮区样式 */
.btn-group {
    margin-bottom: 20px;
    display: flex;
    gap: 10px;
}

/* 表格水平排列容器 */
.table-container {
    display: flex;
    gap: 20px;
    overflow-x: auto;
    /* 横向滚动 */
    padding-bottom: 10px;
    min-height: 400px;
    /* 固定最小高度，避免布局抖动 */
}

/* 单个表格区域样式 */
.table-section {
    min-width: 300px;
    /* 每个表格最小宽度 */
    flex: 1;
    /* 平均分配宽度 */
    padding: 15px;
    border: 1px solid #eee;
    border-radius: 4px;
}

h3 {
    margin-bottom: 15px;
    font-size: 16px;
    font-weight: bold;
    color: #333;
    display: flex;
    align-items: center;
    gap: 10px;
}

.selected-tip {
    margin-top: 8px;
    color: #666;
    font-size: 14px;
}

/* 单元格高亮样式 */
::v-deep .cell-highlight {
    background-color: #e6f7ff !important;
    /* 蓝色高亮 */
    border: 1px solid #91d5ff !important;
}

.el-table {
    --el-table-header-bg-color: #f5f7fa;
    --el-table-header-text-color: #666;
    --el-table-row-hover-bg-color: #f0f0f0;
}

::v-deep .el-table td {
    text-align: center;
    padding: 8px 0;
}

/* 滚动条样式优化 */
.table-container::-webkit-scrollbar {
    height: 6px;
}

.table-container::-webkit-scrollbar-thumb {
    background-color: #ccc;
    border-radius: 3px;
}
</style>